/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tasks.ui;

import common.Observer;
import common.ObserverInterest;
import common.ObserverInterestMap;
import io.FileOpener;
import io.Writer;
import io.XMLWriter;
import java.io.File;

/**
 *
 * @author David
 */
public class ADGTControllerImpl implements ADGTController {

    private FileOpener fo;
    private File currentArchitectureFile;
    private File currentStructureFile;
    private Writer writer;
    private ObserverInterestMap oim;

    public ADGTControllerImpl() {
        this.fo = new FileOpener();
        this.writer = new XMLWriter();
        this.oim = new ObserverInterestMap();
    }

    @Override
    public void openArchitectureFile(File file) {
        fo.openArchitectureFile(file);
        this.currentArchitectureFile = file;
        this.oim.notifyObservers(ObserverInterest.ARCHITECTURE_FILE_OPENED);
    }

    @Override
    public void openStructureFile(File file) {
        fo.openStructureFile(file);
        this.currentStructureFile = file;
        this.oim.notifyObservers(ObserverInterest.STRUCTURE_FILE_OPENED);
    }

    @Override
    public void save() {
        if (this.currentArchitectureFile != null && this.currentStructureFile != null) {
            writer.writeArchitectureFile(this.currentArchitectureFile);
            writer.writeStructureFile(this.currentStructureFile);
        }
    }

    @Override
    public void saveAs(File file) {
        File structureFile;

        if (!file.getPath().endsWith(".xml")) {
            file = new File(file.getPath() + ".xml");
        }
        this.currentArchitectureFile = file;

        String[] fileSplits = file.getPath().split("\\.");
        structureFile = new File(fileSplits[0] + "_structure.xml");

        this.currentStructureFile = structureFile;

        this.save();
    }

    @Override
    public boolean isCurrentFileSet() {
        if (this.currentArchitectureFile != null) {
            return true;
        }
        return false;
    }

    @Override
    public String getCurrentArchitectureFileName() {
        return this.currentArchitectureFile.getName();
    }

    @Override
    public String getCurrentStructureFileName() {
        return this.currentStructureFile.getName();
    }

    @Override
    public void addObserver(Observer observer, ObserverInterest interest) {
        this.oim.put(interest, observer);
    }

    @Override
    public boolean removeObserver(Observer observer) {
        if (this.oim.remove(observer)) {
            return true;
        }
        return false;
    }
}
